import { createRouter, createWebHistory } from "vue-router";
import UserLayout from "@/layout/user/index.vue";
import AdminLayout from "@/layout/admin/index.vue";

const routes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
    meta: { title: "登录" },
  },
  {
    path: "/",
    component: UserLayout,
    redirect: "/home",
    children: [
      {
        path: "home",
        name: "Home",
        component: () => import("@/views/user/home.vue"),
        meta: { title: "首页", requireAuth: true },
      },
      {
        path: "rank",
        name: "Rank",
        component: () => import("@/views/user/rank.vue"),
        meta: { title: "积分排行", requireAuth: true },
      },
    ],
  },
  {
    path: "/admin",
    component: AdminLayout,
    redirect: "/admin/article",
    meta: { requireAuth: true, requireAdmin: true },
    children: [
      {
        path: "article",
        name: "AdminArticle",
        component: () => import("@/views/admin/article.vue"),
        meta: { title: "文章管理" },
      },
      {
        path: "question",
        name: "AdminQuestion",
        component: () => import("@/views/admin/question.vue"),
        meta: { title: "问题管理" },
      },
      {
        path: "user",
        name: "AdminUser",
        component: () => import("@/views/admin/user.vue"),
        meta: { title: "用户管理" },
      },
    ],
  },
  {
    path: "/review",
    name: "Review",
    component: () => import("@/views/review/index.vue"),
    meta: {
      title: "复习计划",
      requiresAuth: true,
    },
  },
  {
    path: "/review/study",
    name: "StudyPlan",
    component: () => import("@/views/review/study.vue"),
    meta: {
      title: "学习计划",
      requiresAuth: true,
    },
  },
  {
    path: "/search",
    name: "Search",
    component: () => import("@/views/search/index.vue"),
    meta: {
      title: "搜索",
      requiresAuth: true,
    },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  const userType = localStorage.getItem("userType");

  // 需要登录的页面
  if (to.matched.some((record) => record.meta.requireAuth)) {
    if (!token) {
      next({
        path: "/login",
        query: { redirect: to.fullPath },
      });
      return;
    }

    // 需要管理员权限的页面
    if (to.matched.some((record) => record.meta.requireAdmin)) {
      if (userType !== "1") {
        next("/");
        return;
      }
    }
  }

  // 已登录用户访问登录页面,重定向到首页
  if (to.path === "/login" && token) {
    next(userType === "1" ? "/admin" : "/");
    return;
  }

  next();
});

export default router;
